//
// Created by Zxy on 2020/9/6.
//

#ifndef UNIONFIND_UNIONFIND2_H
#define UNIONFIND_UNIONFIND2_H
#include <cassert>

class UnionFind2 {
private:
    int *parent;
    int count;
public:
    UnionFind2(int count){
        this->count = count;
        parent = new int[count];
        for(int i = 0; i < count; i++)
            parent[i] = i;
    }
    ~UnionFind2(){
        delete [] parent;
    }
    int find(int p){
        assert(p >= 0 && p < count);
        // 寻找根节点，复杂度O(n)
        while(p != parent[p])
            p = parent[p];
        return p;
    }
    bool isConnected(int p, int q){
        return find(p) == find(q);
    }
    void unionElements(int p, int q){
        int pRoot = find(p);
        int qRoot = find(q);
        if(pRoot == qRoot) return;
        // 让p指向q，复杂度O(1)
        parent[pRoot] = qRoot;
    }
};
#endif //UNIONFIND_UNIONFIND2_H
